<?php

namespace apiend\models\forms;

use Yii;
use common\base\Model;
use common\models\SmsCaptchaForm;
use apiend\models\User;
use common\models\user\UserMeta;
use yii\db\Exception;
use common\helpers\IpHelper;

/**
 * 手机号登录/注册
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class SigninForm extends Model {

    public $mobile;
    public $code;
    //
    private $_user = null;
    //
    private $scope = SmsCaptchaForm::SCOPE_REGISTER;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['mobile', 'code'], 'required'],
            ['mobile', 'string', 'min' => 11, 'max' => 11],
            ['code', 'string', 'min' => 4, 'max' => 6],
            ['mobile', '\common\validators\MobileValidator'],
            ['code', 'validateCaptchaCode'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'mobile' => '手机号',
            'code' => '短信验证码',
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validateCaptchaCode($attribute) {
        if (!$this->hasErrors() && YII_ENV_PROD) {
            $user = $this->getUser();
            if ($user) {
                $this->scope = SmsCaptchaForm::SCOPE_LOGIN;
            }
            $captcha = Yii::$app->cache->get('captcha_' . $this->scope . '_' . $this->mobile);
            if ($captcha == false) {
                $this->addError($attribute, '您输入的' . $this->getAttributeLabel($attribute) . '无效');
            } elseif ($captcha !== $this->$attribute) {
                $this->addError($attribute, $this->getAttributeLabel($attribute) . '不正确');
            }
        }
    }

    /**
     * Finds user by [[mobile]]
     *
     * @return \apiend\models\User|null
     */
    protected function getUser() {
        if ($this->_user === null) {
            $this->_user = User::findByMobile($this->mobile);
        }
        return $this->_user;
    }

    /**
     * Signs user up.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function signin() {
        if (!$this->validate()) {
            $this->dumpError('', $this->getFirstErrors());
        }

        $user = $this->getUser();

        if ($user === null) {
            $user = new User();
            $user->setUsernameByMobile($this->mobile);
            $user->generateAuthKey();

            $meta = new UserMeta();
            $meta->setMobile($this->mobile);
            $meta->avatar = '/attachments/avatar/default.jpg';
            $meta->ip = IpHelper::ip();

            $transaction = Yii::$app->db->beginTransaction();
            try {
                if (!$user->save()) {
                    throw new Exception('账号信息创建失败');
                }
                $meta->id = $user->id;
                if (!$meta->save()) {
                    throw new Exception('用户基本信息保存失败');
                }
                $transaction->commit();
            } catch (Exception $e) {
                $transaction->rollBack();
                $this->dumpError($e->getMessage());
            }
        }

        Yii::$app->cache->delete('captcha_' . $this->scope . '_' . $this->mobile);

        return $user->meta;
    }

}
